# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Codec:
    """会超时"""
    def serialize(self, root):
        """Encodes a tree to a single string.
        :type root: TreeNode
        :rtype: str
        """
        if root:
            res = {"val": root.val,
                   "left": self.serialize(root.left) if root.left else None,
                   "right": self.serialize(root.right) if root.right else None}
            return str(res)
        else:
            return "None"

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        :type data: str
        :rtype: TreeNode
        """
        if type(data) == type("str"):
            data = eval(data)
        if not data:
            return None
        root = TreeNode(data["val"])
        root.left = self.deserialize(data["left"]) if data["left"] else None
        root.right = self.deserialize(data["right"]) if data["right"] else None
        return root


class Codec2:
    def serialize(self, root):
        if not root:
            return ""
        self.res, self.index = "", 0
        self.encode(root)
        return str(self.res[:-1])

    def encode(self, root: TreeNode):
        mid_str = str(root.val) + "." + \
                  (self.encode(root.left) if root.left else "") + "." + \
                  (self.encode(root.right) if root.right else "")
        self.res += mid_str + ","
        self.index += 1
        return str(self.index)

    # def deserialize(self, data: str):
    #     if not data:
    #         return None
    #     data = eval(data)
    #     for index, lists in enumerate(data):
    #         now_root = TreeNode(lists[0])
    #         now_root.left = data[lists[1] - 1] if lists[1] else None
    #         now_root.right = data[lists[2] - 1] if lists[2] else None
    #         data[index] = now_root
    #     return now_root

    def deserialize(self, data: str):
        if not data:
            return None
        data = data.split(",")
        for index, mid_data in enumerate(data):
            # print(mid_data)
            mid_data = mid_data.split(".")
            now_root = TreeNode(int(mid_data[0]))
            now_root.left = data[int(mid_data[1]) - 1] if mid_data[1] else None
            now_root.right = data[int(mid_data[2]) - 1] if mid_data[2] else None
            data[index] = now_root
        return now_root


a1 = TreeNode(1)
a2 = TreeNode(2)
a3 = TreeNode(3)
a4 = TreeNode(4)
a5 = TreeNode(5)
a1.left, a1.right = a2, a3
a3.left, a3.right = a4, a5
a = Codec2()
b = a.serialize(a1)
print(b)
a.deserialize(b)